import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { AppDispatch } from '../store';
import { Version, fetchVersionStatus } from '../store/versionsSlice';
import {
  Box,
  Typography,
  LinearProgress,
  Alert,
} from '@mui/material';

interface VersionStatusProps {
  version: Version;
}

const VersionStatus: React.FC<VersionStatusProps> = ({ version }) => {
  const dispatch = useDispatch<AppDispatch>();

  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (version.status === 'processing') {
      // 每5秒轮询一次状态
      interval = setInterval(() => {
        dispatch(fetchVersionStatus(version.id));
      }, 5000);
    }

    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [dispatch, version.id, version.status]);

  const getProgress = () => {
    switch (version.status) {
      case 'pending':
        return 0;
      case 'processing':
        if (version.download_status === 'success' && version.upload_status === 'success') {
          return 100;
        } else if (version.download_status === 'success') {
          return 66;
        } else if (version.download_status === 'processing') {
          return 33;
        }
        return 0;
      case 'success':
        return 100;
      case 'failed':
        return 100;
      default:
        return 0;
    }
  };

  return (
    <Box mt={2}>
      <Box mb={2}>
        <Typography variant="body2" color="textSecondary" gutterBottom>
          Progress
        </Typography>
        <LinearProgress
          variant="determinate"
          value={getProgress()}
          color={version.status === 'failed' ? 'error' : 'primary'}
        />
      </Box>

      <Box display="flex" gap={2} mb={1}>
        <Typography variant="body2" color="textSecondary">
          Metadata Download: {version.download_status}
        </Typography>
        <Typography variant="body2" color="textSecondary">
          Metadata Upload: {version.upload_status}
        </Typography>
      </Box>

      {version.error_message && (
        <Alert severity="error" sx={{ mt: 2 }}>
          {version.error_message}
        </Alert>
      )}

      <Box mt={1}>
        <Typography variant="body2" color="textSecondary">
          Created: {new Date(version.created_at).toLocaleString()}
        </Typography>
        {version.completed_at && (
          <Typography variant="body2" color="textSecondary">
            Completed: {new Date(version.completed_at).toLocaleString()}
          </Typography>
        )}
      </Box>
    </Box>
  );
};

export default VersionStatus;
